#coding:utf-8
import requests
import json
import re
"""
get_location_city()返回无数据
这条路走不通
"""

class Weather_Get():

    def __init__(self):
        #ip查询
        self.search_ip_url='http://httpbin.org/ip'
        #IP归属地查询
        self.location_url='https://ip.ws.126.net/ipquery?ip={}'
        #获取中国国内城市--number接口
        self.city_number_url='http://static.2ktq.com/sktq/common/city_China.json'
        #天气查询接口
        self.base_weather_url='http://wthrcdn.etouch.cn/weather_mini?citykey={}'
        self.headers={
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
        }
        self.item=self.get_city_item()


    def request(self,url,headers):
        """
        请求url，可自定义请求头
        :param url: 请求的url
        :param headers: 自定义的请求头
        :return: 网页文本数据
        """
        s=requests.session()
        s.keep_alive=False
        try:
            r=s.get(url,headers=headers)
            # r.encoding='utf-8'
            if r.status_code==200:
                # r.encoding = r.apparent_encoding # 会出现推断出错，由ip返回城市的接口，返回的是gbk编码
                return r.text
            else:
                return None
        except requests.exceptions.ConnectionError:
            return None

    def get_location_city(self):
        """
        通过ip定位到当前城市
        :return:所在省市位置信息
        """
        my_headers={
            'Connection': 'keep-alive',
            'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
            'Upgrade-Insecure-Requests': '1'
        }
        _json=json.loads(self.request(self.search_ip_url,headers=my_headers))
        ip=_json.get('origin')
        if ip:
            res=self.request(self.location_url.format(ip),headers=my_headers)
            dingwei_item={}
            dingwei_item['city']=''.join(re.findall('{city:"(.*?)",',res))
            dingwei_item['province']=''.join(re.findall('province:"(.*?)"}',res))
            return dingwei_item

        else:
            return None

    def get_city_item(self):
        res =self.request(self.city_number_url,headers=self.headers)
        item=eval("{'cities':"+res+"}")
        return item

    def get_provinces(self):
        province=[p for p in self.item['cities']]
        #print(province)
        return province

    def get_cities(self,province):
        cities_=self.item['cities'][province]
        cities=[city for city in cities_.keys()]
        return cities

    def get_regions(self,province,city):
        regions_=self.item['cities'][province][city]
        regions=[region for region in regions_.keys()]
        return regions

    def get_city_id_by_add(self,province,city,region=''):
        if region=='':
            city_no=self.item['cities'][province][city][city].replace('CN','')

        else:
            city_no=self.item['cities'][province][city][region].replace('CN','')
        return city_no

    def get_cityid(self,province,city):
        """
        通过省、市在字典中查找对应的城市号
        :param province: 省
        :param city: 市
        :return: 城市号
        """
        if province in self.item['cities'].keys():
            try:
                #河北省唐山市唐山市（通常的省市）
                number=self.item['cities'][province].get(city).get(city).replace('CN','')
                return number
            except AttributeError:
                number=self.item['cities'][province].get(province).get(city).replace('CN','')
                return number
        else:
            return None
            #print('未检索到关于{}{}的信息！'.format(province,city))

    def get_weather(self,number):
        weather_data = json.loads(self.request(self.base_weather_url.format(number),self.headers))
        print('weather_data', weather_data)
        # pprint.pprint(weather_data)
        data=weather_data['data']
        item={}
        yesterday={}
        item_list=[]
        yesterday['日期']=data['yesterday']['date']+'（昨天）'
        item['now']=data['wendu']+'℃'
        item['ganmao']=data['ganmao']
        yesterday['天气']=data['yesterday']['type']
        yesterday['风力风向']=data['yesterday']['fx']+data['yesterday']['fl'].replace('<![CDATA[','').replace(']]>','')
        yesterday['最低气温']=data['yesterday']['low'].replace('低温 ','')
        yesterday['最高气温']=data['yesterday']['high'].replace('高温 ','')
        item_list.append(yesterday)
        count=0
        for weateher in data['forecast']:
            item2={}
            if count==0:
                date=weateher['date']+'（今天）'
            elif count==1:
                date=weateher['date']+'（明天）'
            elif count==2:
                date=weateher['date']+'（后天）'
            else:
                date=weateher['date']+f'（{count-1}天后）'
            item2['日期']=date
            item2['天气'] = weateher['type']
            item2['风力风向']=weateher['fengxiang']+weateher['fengli'].replace('<![CDATA[','').replace(']]>','')
            item2['最低气温'] = weateher['low'].replace('低温 ', '')
            item2['最高气温'] = weateher['high'].replace('高温 ', '')
            item_list.append(item2)
            count+=1
        item['recent']=item_list
        return item

    def get_local_weather(self):
        item=Weather_Get().get_location_city()
        print('kazin: item->',item)
        if item:
            p=item['province']
            c=item['city']
            number=Weather_Get().get_cityid(p,c)
            weather=Weather_Get().get_weather(number)
            return p+c,weather,number
        else:
            return False

if __name__ == '__main__':
    Weather_Get().get_local_weather()
    #Weather_Get().get_regions('北京市','北京市')